import React from 'react';
import {
    PlusOutlined,
    ReloadOutlined,
    CloseCircleFilled,
    SearchOutlined
} from '@ant-design/icons';
import {Button, Divider, Input, Select, Spin} from 'antd';
import {
    find,
    isEmpty,
    map,
    isFunction,
    isArray,
    omit,
    pick,
    forEach,
    unionWith,
    isObject,
    keys, isString
} from 'lodash-es';
import {
    getRandomKey, isNotEmpty,
    isObjectValEqual, QueryFilter,
} from 'jh-utils';
import keyCodes from '../../keyCodes';
import BaseField from "../Base/BaseField";
import debounce from "lodash-es/debounce";
import PropTypes from "prop-types";
import styles from './index.module.less';
import {getDerivedStateFromPropsFunc} from "../Base/helper/lifeCycle";
import trim from "lodash-es/trim";
import findIndex from "lodash-es/findIndex";

const {Option} = Select;
const InputGroup = Input.Group;

const updateListWithValue = (list, value, primaryKey = 'code') => {

    if (!isEmpty(value) && isArray(list)) {
        let tmpInd = findIndex(list, (lItem) => (
            lItem && lItem[primaryKey] === value[primaryKey]
        ));
        if (-1 === tmpInd) {
            list = [value, ...list];
        }
    }
    return list;
};

const staticPros = {

    /**
     * 是否多选
     */
    multi: PropTypes.bool,
    /**
     * 查找器的中文描述
     */
    finderName: PropTypes.string,
    /**
     * 回显的属性名。以 ';' 分隔
     */
    descField: PropTypes.string,
    /**
     * 下拉列表数据
     *
     * */
    compData: PropTypes.arrayOf(PropTypes.object),
    /**
     * compData 对象数据的 主键 属性名
     * @default 'code'
     *
     * */
    primaryKey: PropTypes.string,
    /**
     * compData 对象数据的 名称 属性名
     * @default 'name'
     *
     * */
    nameKey: PropTypes.string,
    /**
     * 组件是否课件。
     * 如果为 false，则此组件隐藏不显示，但组件逻辑正常，仍然会请求数据，并在加载数据之后回调 onDataLoad
     * @default true
     *
     */
    visible: PropTypes.bool,
    disabled: PropTypes.bool,
    readOnly: PropTypes.bool,
    /**
     * 是否可以打开下拉框。（部分场景下，不需要下拉框）
     * @type {boolean}
     */
    needDropdown: PropTypes.bool,
    /**
     * 是否显示 placeholder
     */
    needPH: PropTypes.bool,
    /**
     * 是否需要“弹框选择”
     */
    needMenu: PropTypes.bool,
    /**
     * 是否显示“快速添加”按钮
     */
    needAdd: PropTypes.bool,
    /**
     * 是否显示“查看所有”按钮
     */
    needList: PropTypes.bool,
    /**
     * 是否显示“刷新”按钮
     */
    needRefresh: PropTypes.bool,
    /**
     * 是否需要“输入框的右侧按钮”
     */
    needMenuBtn: PropTypes.bool,
    /**
     * dropdown 底部按钮的操作回调
     * @type {function({type: string})}
     */
    onDDFooterAction: PropTypes.func,
    /**
     * Function 自定义 Option 中的文本显示
     */
    renderItem: PropTypes.func,
    /**
     * Function 自定义 Option 中的 text 属性值
     */
    renderOptionText: PropTypes.func,
    /**
     * 自定义 dropdown 的底部
     */
    dropdownFooter: PropTypes.any,
    /**
     * 自定义下拉列表的请求方法
     * function(ajaxData)
     */
    fetchList: PropTypes.func,
    /**
     * 获得下拉列表数据之后的回调
     * function(list)
     */
    onDataLoad: PropTypes.func,
    /**
     * 是否默认打开下拉列表。默认false
     *  true：默认打开下拉框，并立即请求数据。
     *  false：需要手动打开，且手动打开时才会请求数据。
     */
    defaultOpen: PropTypes.bool,
};
/**
 * 对象类型选择-下拉框
 * @description 用于选择对象类型的数据
 */
export default class ObjectSelect extends BaseField {

    static propTypes = {
        ...BaseField.propTypes,
        ...staticPros
    };

    static defaultProps = {
        primaryKey: 'code',
        nameKey: 'name',
        descField: 'name',
        style: {},
        needDropdown: true,
    };

    static getDerivedStateFromProps(nextProps, preState) {
        let reObj = getDerivedStateFromPropsFunc(nextProps, preState, (changedValue) => {
            // @param changedValue 即 nextProps 中有变化的 value 或 defaultValue 的值。
            // 在这个方法里返回需要更新到 state 里的值。
            // （注：defaultValue 的处理已经在 getDerivedStateFromPropsFunc 中默认处理，所以这里不用返回了）
            const tmpO = {
                value: changedValue || {},
                propsValue: changedValue,
                originValue: changedValue,
            };
            // if (!isObjectValEqual(nextProps, {value: preState.propsValue}, ['value'])) {
            //     const tmpValue = nextProps.value || {};
            //     tmpO.inputVal = tmpValue[nextProps.primaryKey]// 输入框的值
            // }
            return tmpO;
        });

        if ('compData' in nextProps) {

            if (!isObjectValEqual(nextProps, {compData: preState.propList}, ['compData'])) {
                return {
                    ...(reObj || {}),
                    list: nextProps.compData || [],
                    propList: nextProps.compData,
                    originList: nextProps.compData
                }
            }
        }
        return reObj;
    }

    /**
     * dropdown 的 dom 节点
     * 用于设置下拉框的最小宽度
     * @type {{current: null}}
     */
    ddRef = React.createRef();
    /**
     * dropdown 的属性
     * @type {{}}
     */
    ddProps = {};
    /**
     * 是否需要强制请求下拉列表的数据。
     * 每次调用 addEditBeforeHandler 时，设置为 true，
     * 然后在 hdlClickSelect 中，设置为 false
     * @type {boolean}
     */
    needForceFetch = true;
    /**
     * 是否可以请求数据。
     *  外部可通过设置此参数，阻止组件请求数据。
     *  比如：afc “凭证明细-核算因素”的 beforeCb
     * @type {boolean}
     */
    canFetchData = true;

    constructor(props) {
        super(props);
        this.hdlSearch = debounce(this.hdlSearch.bind(this), 500);
    }

    moreCommonProps() {
        return [
            ...super.moreCommonProps(),
            ...keys(staticPros)
        ];
    }

    initState(props) {
        const {compData} = props;
        // console.log('initState props', props);
        const value = props.value || props.defaultValue || {};
        return {
            ...super.initState(props),
            inputVal: '', //value[props.primaryKey], // 输入框的值
            value: value,
            list: isArray(compData) ? compData : [],
            propList: compData,
            originList: compData,
            loading: false,
            isShowModal: false, // 是否显示弹框
            open: props.defaultOpen,
            randomKey: getRandomKey(),
        };
    }

    componentDidMount() {
        super.componentDidMount && super.componentDidMount();

        if (!isEmpty(this.state.list)) {
            this.runPropsFunc('onDataLoad')(this.state.list);

        } else if (this.getPropsByName('defaultOpen')) {
            // 如果是“默认打开下拉列表”，则需要发起请求
            this.fetchData();
        }

        if (this.ddRef.current && this.ddRef.current.offsetWidth < 150) {
            const ddProps = {};
            // console.log('>>> this.ddRef.current.offsetWidth', this.ddRef.current.offsetWidth);
            // this.ddRef.current.offsetWidth
            ddProps.dropdownMatchSelectWidth = false;
            ddProps.dropdownStyle = {width: 150};
            this.ddProps = ddProps;
            this.setState({randomKey: getRandomKey()});
        }
    }

    setValue(value, afterCb) {
        this.state.inputVal = ''; // !isEmpty(value) ? value[this.getPropsByName('primaryKey')] : '';
        super.setValue(value, afterCb);
    }

    /**
     * 设置下拉列表数据
     * @param data {[{code?: string, name?:string}]}
     * @param afterCb
     */
    setData(data, afterCb) {
        this.setState({
            list: data,
            originList: data
        }, afterCb)
    }

    lastFetchId = 1;

    /**
     * 请求列表数据
     */
    fetchData() {
        this.runBeforeCbs();

        if (!this.canFetchData) return;

        const {fetchList} = this.getProps();

        if (!isFunction(fetchList)) return;

        const {inputVal} = this.state;
        this.lastFetchId += 1;
        const fetchId = this.lastFetchId;
        const searchData = {
            fuzzyMatch: 'code,name,spellCode',
            search: inputVal
        };
        const queryFields = !isEmpty(this.queryFields) ? this.queryFields : [];
        const filter = (this.filter && this.filter.toJson) ? this.filter.copy() : new QueryFilter(QueryFilter.AND);
        filter.formatBySearchData(searchData);

        this.setState({loading: true});

        const fetchReturn = fetchList({
            inputVal,
            queryFields,
            filter: filter.toJson(),
            filterIns: filter,
            searchData: searchData,
            startIndex: 0,
            maxResults: 100
        }, {}, this);

        if (fetchReturn instanceof Promise) {
            fetchReturn.then((rsp) => {

                if (fetchId !== this.lastFetchId) {
                    // 控制请求时序
                    return rsp;
                }

                let newList = [];

                if (rsp && rsp.status === 200) {
                    const rspData = rsp.data;
                    newList = isArray(rspData) ? rspData : (
                        isArray(rspData.results) ? rspData.results : []
                    );
                }

                this.setState({
                    list: newList,
                    loading: false
                }, () => {
                    this.runPropsFunc('onDataLoad')(newList);
                    // this._tmpFunc();
                });
                return rsp;
            });
        } else {
            this.setState({loading: false});
        }

    }

    /**
     * 设置“组件的值-编辑前”事件处理。重复调用此方法，可实现“多次事件绑定”
     * @param cb {function(compIns: {})} // compIns 是当前编辑组件的实例
     */
    addEditBeforeHandler(cb) {
        // 设置 needForceFetch = true，使得再次点开下拉弹框时，重新请求一次接口
        this.needForceFetch = true;
        super.addEditBeforeHandler(cb);
    }

    // _tmpFunc() {
    //     setTimeout(() => {
    //         let selDom = document.getElementsByClassName(this.COMP_ID);
    //         console.log('selDom', selDom);
    //         if (selDom && selDom[0] && selDom[0].getElementsByClassName) {
    //             let inputDom = selDom[0].getElementsByClassName('ant-select-selection-search-input');
    //             if (inputDom && inputDom[0]) {
    //                 console.log('this.state.inputVal', this.state.inputVal);
    //                 const value = this.state.inputVal || '';
    //                 let element = inputDom[0];
    //                 element.value = value;
    //                 element.unselectable="off";
    //                 element.readonly="false";
    //             }
    //         }
    //     }, 100);
    // }

    /**
     * 是否多选
     */
    isMulti() {
        return this.getPropsByName('multi');
    }

    /**
     * “点击下拉框”的回调
     * 如果下拉列表为空，则刷新数据
     * @param open {boolean} 当前是否打开了下拉框
     */
    hdlClickSelect(open) {
        // console.log('hdlClickSelect open', open);
        this.setState({open});

        if (open) {
            if (isEmpty(this.state.list) || this.needForceFetch) {
                this.needForceFetch = false;
                this.fetchData();
            } else {
                this.runBeforeCbs();
            }
        }
        // this._tmpFunc();
    }

    /**
     * “选中下拉数据”之后的回到
     * @param value
     * @param options
     */
    hdlValueChange(value, options = {}) {

        if (isObject(value)) {
            super.hdlValueChange(value);
        } else {
            const primaryKey = this.getPropsByName('primaryKey');
            const multi = this.isMulti();
            let data = find(this.state.list, (v) => (v[primaryKey] == value));
            if (multi && !isEmpty(data)) {
                data = [data];
            }
            super.hdlValueChange(data || null);
        }

        if (isEmpty(value)) {
            this.hdlSearch('');
        }
    }

    /**
     * “触发筛选”之后的回调
     * @param value
     */
    hdlSearch(value) {
        console.log('hdlSearch', value);
        this.setState({inputVal: trim(value)}, () => {
            this.fetchData();
        });
    }

    hdlInputKeyDown(e) {
        let keyCode = e.keyCode || e.which || e.charCode;
        // 禁止浏览器的 F5 刷新，触发组件的刷新方法
        if (keyCodes.f5 === keyCode) {
            e.preventDefault();
            this.fetchData();
        }
    };

    actionTypes = {
        add: 'add',
        list: 'list',
        refresh: 'refresh',
        detail: 'detail',
    };

    /**
     * 点击 dropdown 底部“添加”按钮的回调
     * @param e
     */
    hdlAddAction(e) {
        e.preventDefault();
        this.runPropsFunc('onDDFooterAction')({type: this.actionTypes.add});
    }

    /**
     * 点击 dropdown 底部“查看所有”按钮的回调
     * @param e
     */
    hdlListAction(e) {
        e.preventDefault();
        let value = this.getValue();
        this.runPropsFunc('onDDFooterAction')({
            type: (!isEmpty(value) && value.id > 0 ? this.actionTypes.detail : this.actionTypes.list)
        });
    }

    /**
     * 点击 dropdown 底部“刷新”按钮的回调
     * @param e
     */
    hdlRefreshAction(e) {
        e.preventDefault();
        this.runPropsFunc('onDDFooterAction')({type: this.actionTypes.refresh});
    }

    /**
     * 处理“输入-筛选”逻辑
     * @param inputVal {string}  输入框的值
     * @param opt {React.ReactElement} 下拉框的选项节点
     * @return {boolean} 返回 true 表示符合筛选条件
     */
    hdlFilter(inputVal, opt) {

        if ('undefined' !== typeof opt.props.isempty) return true;

        inputVal = `${inputVal || ''}`.toLocaleLowerCase();
        const text = `${opt.props.text || ''}`.toLocaleLowerCase();
        let isOk = -1 !== text.indexOf(inputVal);

        if (!isOk && opt.props.title) {
            const title = `${opt.props.title || ''}`.toLocaleLowerCase();
            isOk = -1 !== title.indexOf(inputVal);
        }
        if (!isOk && opt.props.code) {
            const code = `${opt.props.code || ''}`.toLocaleLowerCase();
            isOk = -1 !== code.indexOf(inputVal);
        }
        if (!isOk && opt.props.spellcode) {
            const spellCode = `${opt.props.spellcode || ''}`.toLocaleLowerCase();
            isOk = -1 !== spellCode.indexOf(inputVal);
        }
        return isOk;
    }

    /**
     * “弹框中-确认选择”的回调
     * @param checkedList {[{}]} 选中的数据
     */
    hdlChooseOk(checkedList) {
        const multi = this.isMulti();
        const newList = unionWith(this.state.list || [], checkedList,
            (row1, row2) => (row1.id === row2.id)
        );
        let checkedData = checkedList[0];

        if (multi) {
            checkedData = checkedList;
        }

        this.setState({isShowModal: false, list: newList, inputVal: ''}, () => {
            super.hdlValueChange(checkedData);
            // this.hdlValueChange(checkedItem[this.getPropsByName('primaryKey')] || '');
        });
    }

    /**
     * “弹框中-取消选择”的回调
     */
    hdlChooseCancel() {
        this.setState({isShowModal: false});
    }

    /**
     * 点击右侧菜单之后的回调
     */
    hdlClickMenu() {
        // 执行“通过 addEditBeforeHandler 设置”的回调
        this.runBeforeCbs();

        if (!this.canFetchData) return;

        this.setState({isShowModal: true, open: false});
    }

    getOptionProps(opt, oK, props) {
        const {primaryKey, nameKey, renderItem, renderOptionText} = props;
        let text = '',
            optionText = '',
            title = '';

        // 选中值之后回显的内容
        if (isFunction(renderOptionText)) {
            text = renderOptionText(opt);
        } else {
            text = opt[nameKey] || opt.code;
        }

        if (isEmpty(text)) {
            text = opt.code || '';
        }

        // 下拉列表显示的内容
        if (isFunction(renderItem)) {
            optionText = renderItem(opt) || opt.code;
        } else {
            optionText = <>
                <span className={'text-gray'}>{opt.code}</span> {opt[nameKey]}
            </>;
        }
        title = text;

        return {
            key: oK,
            value: opt[primaryKey],
            text,
            title,
            code: opt['code'],
            spellcode: opt['spellCode'],
            children: optionText,
        };
    }

    dropdownRender(menu) {
        const {loading, value} = this.state;
        const nameKey = this.getPropsByName('nameKey');
        const primaryKey = this.getPropsByName('primaryKey');
        const appTxt = this.getPropsByName('finderName');
        const dropdownFooter = this.getPropsByName('dropdownFooter');
        const needMenu = this.getPropsByName('needMenu');
        const needAdd = this.getPropsByName('needAdd');
        const needList = this.getPropsByName('needList');
        const needRefresh = this.getPropsByName('needRefresh');
        let addTxt = this.formatMsgByCn('添加');
        let needDDFooterAction = needAdd || needList || needRefresh;

        const ddFooter = dropdownFooter ? dropdownFooter : (
            !needDDFooterAction ? null :
                <>
                    <Divider style={{margin: 0}}/>
                    <div style={{position: 'relative', padding: 6, height: '32px'}}>
                        {
                            needAdd && (
                                <Button type='link'
                                        size={'small'}
                                    // onClick={this.hdlAddAction.bind(this)}
                                        onMouseDown={this.hdlAddAction.bind(this)}
                                        title={`${addTxt} ${appTxt || ''}`}
                                        style={{textAlign: 'left', padding: 0, fontSize: 12}}>
                                    <PlusOutlined/>
                                </Button>
                            )
                        }

                        {
                            needRefresh && (
                                <Button size={'small'}
                                        type={'link'}
                                        title={`${this.myFormatMessage('crud.refresh')} (F5)`}
                                        style={{float: 'right', marginRight: 0}}
                                        onMouseDown={this.hdlRefreshAction.bind(this)}>
                                    <ReloadOutlined spin={this.state.loading || loading === true}/>
                                </Button>
                            )
                        }
                        {
                            needMenu && (
                                <Button size={'small'}
                                        type={'link'}
                                        title={this.myFormatMessage('act.adv.query')}
                                        style={{float: 'right', fontSize: 14}}
                                        onMouseDown={this.hdlClickMenu.bind(this)}>
                                    <SearchOutlined/>
                                </Button>
                            )
                        }
                        {
                            // needList && (
                            //     <Button size={'small'}
                            //             title={
                            //                 isEmpty(value) ?
                            //                     this.myFormatMessage('act.view.all', {name: appTxt}) :
                            //                     this.myFormatMessage('act.view', {name: value[nameKey] || value[primaryKey]})
                            //             }
                            //             className={styles.ddJumpBtn}
                            //             onClick={this.hdlListAction.bind(this)}>
                            //         <DoubleRightOutlined/>
                            //     </Button>
                            // )
                        }
                    </div>
                </>
        );
        // const menuLen = menu.props.menuItems ? menu.props.menuItems.length : 0;
        // console.log('>>>', menu);
        return (
            <>
                <Spin spinning={this.state.loading || loading === true}>
                    {menu}
                    {
                        // 'ObjectBox' === this.props.displayName ? null : (
                        //     menuLen <= 1 && (
                        //         <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
                        //     )
                        // )
                    }
                </Spin>
                {ddFooter}
            </>
        );
    }

    genStateList() {

        return updateListWithValue(this.state.list || [], this.state.value, this.getPropsByName('primaryKey'));
    }

    inputRender(props) {
        const {needMenu, needPH, disabled, primaryKey, nameKey, autoFocus, style, multi} = props;
        const stateValue = this.state.value || (multi ? [] : {});
        const value = stateValue[primaryKey] || stateValue[nameKey] || '';
        const compData = this.genStateList(); //this.state.list || [];
        const ddProps = this.ddProps;
        let placeHolder = this.myFormatMessage('comp.select.placeholder');
        let optionMoreProps = {
            text: placeHolder
        };

        return (
            <Select
                showSearch
                allowClear
                autoFocus={autoFocus}
                showArrow={!needMenu}
                filterOption={isFunction(this.getPropsByName('fetchList')) ? false : this.hdlFilter.bind(this)}
                {...omit(props, this.commonProps)}
                value={value}
                open={this.state.open}
                defaultActiveFirstOption={'' === value}
                onDropdownVisibleChange={this.hdlClickSelect.bind(this)}
                onChange={this.hdlValueChange.bind(this)}
                onInputKeyDown={this.hdlInputKeyDown.bind(this)}
                onSearch={this.hdlSearch.bind(this)}
                loading={this.state.loading}
                style={style}
                className={`${this.COMP_ID} ${props.className || ''}`}
                optionLabelProp={'text'}
                dropdownRender={this.dropdownRender.bind(this)}
                disabled={disabled}
                {...ddProps}
                ref={(ref) => {
                    this.nodeRef = ref;
                }}
            >
                {
                    needPH && (
                        <Option value="" {...optionMoreProps}>{placeHolder}</Option>
                    )
                }
                {map(compData, (opt, oK) => {
                    const tProps = this.getOptionProps(opt, oK, props);
                    return (
                        <Option {...omit(tProps, ['children'])}>
                            {tProps.children}
                        </Option>
                    );
                })}
            </Select>
        )
    }

    /**
     * 处理“回显的内容”
     */
    dealPreviewContent() {
        const {multi} = this.getProps();
        const stateValue = this.state.value || (multi ? [] : {});
        let prevStr = '';

        if (multi && !isEmpty(stateValue) && stateValue[0]) {
            // prevStr = `${stateValue[0].code} ${stateValue[0].name}${stateValue.length > 1 ? '...' : ''}`;
            prevStr = this.dealPreview4Multi();

        } else if (!isEmpty(stateValue)) {
            prevStr = this.dealPreviewSingle(stateValue);
            // prevStr = this.runPropsFunc('renderOptionText')(stateValue) || stateValue[nameKey] || prevStr;
        }
        return prevStr;
    }

    /**
     * 处理“单选情况下的回显内容”
     */
    dealPreviewSingle(item) {
        const nameKey = this.getPropsByName('nameKey') || 'name';
        const tmpStr = this.runPropsFunc('renderOptionText')(item);
        return isNotEmpty(tmpStr) ? tmpStr : item[nameKey];
    }

    /**
     * 处理“多选情况下的回显内容”
     */
    dealPreview4Multi(showAll = false) {
        const {value} = this.state;
        const nameKey = this.getPropsByName('nameKey') || 'name';
        let valArr = [];
        let valLen = value ? value.length : (isEmpty(value) ? 0 : 1);

        forEach(value, (item, ind) => {

            if (showAll || (!showAll && ind < 5)) {
                let tmpStr = this.dealPreviewSingle(item);
                valArr.push(isString(tmpStr) ? tmpStr : item[nameKey]);
            } else {
                valArr.push('...');
                return false; // 退出 forEach
            }
        });
        return this.myFormatMessage('selected.cnt', {count: valLen}) + ': ' + valArr.join(', ');
    }

    selectRender(props = {}) {
        const {disabled, style, multi, needDropdown, primaryKey, nameKey, autoFocus, descField} = props;
        const stateValue = this.state.value || (multi ? [] : {});
        const valueLen = multi && stateValue ? stateValue.length : (isEmpty(stateValue) ? 0 : 1);
        let tmpStr = this.dealPreviewContent();
        let prevStr = isNotEmpty(tmpStr) ? tmpStr : this.myFormatMessage('comp.select.placeholder');

        // if (multi && !isEmpty(stateValue) && stateValue[0]) {
        //     // prevStr = `${stateValue[0].code} ${stateValue[0].name}${stateValue.length > 1 ? '...' : ''}`;
        //     prevStr = this.dealPreview4Multi();
        //
        // } else if (!isEmpty(stateValue)) {
        //     prevStr = this.dealPreviewSingle(stateValue) || prevStr;
        //     // prevStr = this.runPropsFunc('renderOptionText')(stateValue) || stateValue[nameKey] || prevStr;
        // }

        return (
            <>
                {
                    (multi || false === needDropdown) ? (
                        <Button
                            autoFocus={autoFocus}
                            className={'hover-wrap'}
                            style={{
                                ...style,
                                padding: '0 8px',
                                textAlign: 'left',
                                lineHeight: '26px',
                                textOverflow: 'ellipsis',
                                overflow: 'hidden',
                                whiteSpace: 'unset'
                            }}
                            title={isString(prevStr) ? prevStr : ''}
                            disabled={disabled}
                            onClick={() => {
                                this.setState({isShowModal: true});
                            }}>
                            {/*{*/}
                            {/*    (multi && valueLen > 0) && (*/}
                            {/*        this.myFormatMessage('selected.cnt', {count: valueLen})*/}
                            {/*        // <span style={{*/}
                            {/*        //     float: 'left',*/}
                            {/*        //     fontWeight: 'bold',*/}
                            {/*        //     marginRight: 4*/}
                            {/*        // }}>{*/}
                            {/*        //     this.myFormatMessage('selected.cnt', {count: valueLen})*/}
                            {/*        // }: </span>*/}
                            {/*    )*/}
                            {/*}*/}
                            {prevStr}

                            {
                                valueLen > 0 && (
                                    <Button type={'link'}
                                            className={'hover-show text-gray f12'}
                                            onClick={(e) => {
                                                e.preventDefault();
                                                e.stopPropagation();
                                                this.hdlChooseOk([]);
                                            }}
                                            title={this.formatMsgByCn('清空')}
                                            style={{
                                                padding: '5px 8px',
                                                lineHeight: '16px',
                                                position: 'absolute',
                                                right: 0,
                                                top: 0
                                            }}>
                                        <CloseCircleFilled/>
                                    </Button>
                                )
                            }
                        </Button>
                    ) : (
                        this.inputRender(props)
                    )
                }
                <div ref={this.ddRef} style={{display: 'block'}}/>
            </>
        )
    }

    /**
     * 自定义“弹框中-选择区域”的渲染
     * @param props
     * @return {null}
     */
    chooseRender(props) {
        return null;
    }

    mainRender(context) {
        const props = this.getProps();
        if (false === props.visible) return null;

        // 只读
        if (props.readOnly) {
            // console.log('readOnly', this);
            return this.dealPreviewContent();
        }

        const {style, needMenu, needMenuBtn} = props;
        const styleO = style || {};
        let noNeedRightBtn = false === needMenu || false === needMenuBtn;
        // const mainWidth = isNumber(styleO.width) ? styleO.width : `calc(100% - ${needMenu ? '28px' : '0px'})`;

        const groupStyle = pick(styleO, ['width', 'height']);
        const objectBoxStyle = {
            ...styleO,
            // minWidth: '100px',
            width: !noNeedRightBtn ? `calc(100% - 28px)` : '100%'
        };

        return <>
            <InputGroup compact={!noNeedRightBtn} style={{minWidth: 100, zIndex: 1, ...groupStyle}}>
                {this.selectRender({...props, style: objectBoxStyle})}
                {
                    !noNeedRightBtn && (
                        <Button
                            title={this.myFormatMessage('act.adv.query')}
                            disabled={props.disabled}
                            className={styles.menuBtn}
                            onClick={this.hdlClickMenu.bind(this)}>
                            {/*<UnorderedListOutlined/>*/}
                            <SearchOutlined/>
                        </Button>
                    )
                }
            </InputGroup>
            {
                needMenu && this.state.isShowModal && (
                    this.chooseRender(props)
                )
            }
        </>;
    }
}